package com.example;

import java.util.List;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.datasource.DataSourceFactory;
import org.apache.ibatis.datasource.pooled.PooledDataSourceFactory;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

/**
 * Hello world!
 *
 */
public class App {
    public static void main(String[] args) {
        // 属性类
        Properties properties = new Properties();
        properties.setProperty("driver", "com.mysql.cj.jdbc.Driver");
        properties.setProperty("url", "jdbc:mysql://127.0.0.1:3306/test-mybatis");
        properties.setProperty("username", "root");
        properties.setProperty("password", "111222");

        // 数据源工厂类
        DataSourceFactory dataSourceFactory = new DataSourceFactory() {
            private Properties properties;

            @Override
            public void setProperties(Properties props) {
                this.properties = props;
            }

            @Override
            public DataSource getDataSource() {
                PooledDataSourceFactory pooledDataSourceFactory = new PooledDataSourceFactory();
                pooledDataSourceFactory.setProperties(properties);
                return pooledDataSourceFactory.getDataSource();
            }
        };
        dataSourceFactory.setProperties(properties);
        DataSource datasource = dataSourceFactory.getDataSource();
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        // 新建环境
        Environment environment = new Environment("development", transactionFactory, datasource);
        // 新建配置
        Configuration configuration = new Configuration(environment);
        // 新建映射器
        configuration.addMapper(UserMapper.class);
        // 构建SQL会话
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
        // 启动SQL会话
        SqlSession session = sqlSessionFactory.openSession();
        // 获得映射器
        UserMapper mapper = session.getMapper(UserMapper.class);
        // 查询多条记录
        List<User> user = mapper.selectAll();
        // 遍历结果
        user.forEach((item) -> {
            System.out.println(item.getName());
        });
    }
}
